package com.gui.lock.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;


public class RedisLockProvider {

    private final StringRedisTemplate stringRedisTemplate;

    private final String businessType;

    private static final String COMMON_KEY_PREFIX = "gui:";

    public RedisLockProvider(StringRedisTemplate stringRedisTemplate, String businessType) {
        if (stringRedisTemplate == null) {
            throw new IllegalArgumentException("StringRedisTemplate cannot be null");
        }
        this.stringRedisTemplate = stringRedisTemplate;
        this.businessType = businessType;
    }

    public boolean tryLock(long timeout) {
        String key = COMMON_KEY_PREFIX + this.businessType;
        String threadName = Thread.currentThread().getName();
        Boolean lockFlag = stringRedisTemplate.opsForValue().setIfAbsent(key, threadName, timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(lockFlag);
    }


    public void unLock() {
        String key = COMMON_KEY_PREFIX + this.businessType;
        stringRedisTemplate.delete(key);
    }


}
